package com.naiterui.ehp.bp.utils.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.conn.util.InetAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author guoyongxiang
 * @since 1.0.0
 */
public class IPUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(IPUtil.class);
    private static Pattern pattern =
        Pattern.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}");

    /**
     * 获取点分IP地址 IPManager.isDottedIp()<BR>
     * <P>
     * Author : wugaoping
     * </P>
     * <P>
     * Date : 2013-4-7
     * </P>
     * 
     * @param ipString
     *            IP地址字符串
     * @return 返回IP地址字符串
     */
    private static String isDottedIp(String ipString) {
        if (ipString != null) {
            Matcher matcher = pattern.matcher(ipString);
            if (matcher.matches()) {
                return matcher.group();
            }
        }

        return null;
    }

    /**
     * 获取IP地址 IPManager.getIp()<BR>
     * <P>
     * Author : wugaoping
     * </P>
     * <P>
     * Date : 2013-4-7
     * </P>
     * 
     * @param request
     *            http请求头
     * @return 提取IP地址信息
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = isDottedIp(request.getHeader("Proxy-Client-IP"));
            if (ip != null) {
                return ip;
            }
        } else {
            if (ip.indexOf(",") != -1) {
                String[] s = ip.split(",");
                for (String value : s) {
                    if (value != null && !"".equals(value) && !"unknown".equals(value)) {
                        ip = isDottedIp(value.trim());
                        if (ip != null) {
                            return ip;
                        }
                    }
                }
            } else if (ip.indexOf(";") != -1) {
                String[] s = ip.split(";");
                for (String value : s) {
                    if (value != null && !"".equals(value) && !"unknown".equals(value)) {
                        ip = isDottedIp(value.trim());
                        if (ip != null) {
                            return ip;
                        }
                    }
                }
            } else {
                if ("unknown".equals(ip)) {
                    ip = isDottedIp(ip.trim());
                    if (ip != null) {
                        return ip;
                    }
                }
            }
        }

        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = isDottedIp(request.getHeader("WL-Proxy-Client-IP"));
            if (ip != null) {
                return ip;
            }
        }

        if ((ip != null) && (ip.indexOf(' ') != -1)) {
            ip = isDottedIp(ip.substring(0, ip.indexOf(' ')));
            if (ip != null) {
                return ip;
            }
        }

        if (ip == null) {
            if ((request.getHeader("x-forwarded-for") != null) || (request.getHeader("Proxy-Client-IP") != null)
                || (request.getHeader("WL-Proxy-Client-IP") != null)) {
                Enumeration headers = request.getHeaderNames();
                while (headers.hasMoreElements()) {
                    String headerName = headers.nextElement().toString();
                    LOGGER.debug(headerName + " --> " + request.getHeader(headerName));
                }

                LOGGER.debug("request.getRemoteAddr:{}", request.getRemoteAddr());
            }

            ip = request.getRemoteAddr();
        }

        return ip;
    }

    /**
     * 获取真实IP IPUtil.getRealIP()
     * 
     * @Author Gaoll
     * @Date 2016年8月24日
     * @since HZD-1.0.0
     * @return
     */
    public static String getRealIP() {

        String ipaddress = "";
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = nif.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (inet.hasMoreElements()) {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip.getHostAddress())
                        && ip.isSiteLocalAddress()) {
                        return ip.getHostAddress();
                    }
                }

            }
        } catch (SocketException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return ipaddress;

    }
}
